package com.code.bz.interceptors;

import com.code.bz.annotations.LoginAuth;
import com.code.bz.exceptions.BusinessException;
import com.code.bz.managers.HttpManager;
import com.code.bz.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 已登录权限验证拦截器 备注：通过{@link LoginAuth}配合使用
 *
 * @author xiaoyaowang
 */
@Slf4j
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Resource
    private HttpManager httpManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();

            if (clazz.isAnnotationPresent(LoginAuth.class) || method.isAnnotationPresent(LoginAuth.class)) {
                String token = request.getHeader("token");
                if (StringUtils.isBlank(token)) {
                    throw new BusinessException(ResultCode.USER_NOT_LOGGED_IN);
                }
                Boolean verifyToken = httpManager.verifyToken(token);
                if (!verifyToken) {
                    throw new BusinessException(ResultCode.USER_NOT_LOGGED_IN);
                }
            }

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        // nothing to do
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // nothing to do
    }

}
